package com.hex.liyue.commonmodule.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;

import com.hex.liyue.commonmodule.bean.PhoneNumber;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by yukuo on 2016/5/11.
 * 这是一个获取手机联系人信息的工具类
 */
public class PhoneContactUtils {
    public interface OnLoadSuccessListener {
        void onSuccess(List<PhoneNumber> list);

        void onFailure();
    }

    /**
     * 这是一个返回一个联系人信息列表集合的方法
     *
     * @param context 上下文
     * @return
     */
    public static void getPhoneNumberData(final Context context, final OnLoadSuccessListener onLoadSuccessListener) {
        new Thread() {
            @Override
            public void run() {
                List<PhoneNumber> list = new ArrayList<PhoneNumber>();
                ContentResolver cr = context.getContentResolver();
                Cursor cursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
                if (cursor != null) {
                    while (cursor.moveToNext()) {
                        int PhoneName = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
                        int phoneNumbe = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                        PhoneNumber phoneNumber = new PhoneNumber();
                        //电话号码
                        phoneNumber.setNumber(cursor.getString(phoneNumbe).replace(" ",""));
                        L.i("手机号码", cursor.getString(phoneNumbe).replace(" ",""));
                        //名字
                        phoneNumber.setName(cursor.getString(PhoneName));
                        L.i("名字", cursor.getString(PhoneName));
                        list.add(phoneNumber);
                    }
                    if (onLoadSuccessListener != null) {
                        onLoadSuccessListener.onSuccess(list);
                    }
                } else {
                    if (onLoadSuccessListener != null) {
                        onLoadSuccessListener.onFailure();
                    }
                }
            }
        }.start();
    }
}
